package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.UserStatus;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        //1、根据ids查询用户列表
        List<User> userList = this.listByIds(ids);
        //2、List<User> 转换为List<UserVo>
        List<UserVO> userVOList = BeanUtil.copyToList(userList, UserVO.class);

        //3、根据用户id集合查询用户地址列表 select * from address where user_id in (?,?,?)
        List<Address> addressList = Db.lambdaQuery(Address.class).in(Address::getUserId, ids).list();
        /*
        上面的查询结果是List<Address> ----> List<AddressVO>
        每个用户都有可能多个地址；我们期望 Map<用户id，地址列表>  例如：<1, List<AddressVO>>
        如果有上述的数据结构的话；那么可以遍历List<UserVO>，然后每个用户从上面的map找自己的地址列表
         */
        List<AddressVO> addressVOList = BeanUtil.copyToList(addressList, AddressVO.class);
        Map<Long, List<AddressVO>> addressVoMap =
                addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));

        for (UserVO userVO : userVOList) {
            List<AddressVO> addressVOS = addressVoMap.get(userVO.getId());
            userVO.setAddresses(addressVOS);
        }
        //4、返回数据
        return userVOList;
    }

    @Override
    public UserVO queryUserAndAddress(Long id) {
        //1、根据id查询用户
        User user = this.getById(id);
        //2、转换为userVo
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        //3、根据id查询用户地址列表 select * from address where user_id=?
        List<Address> addressList = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();

        userVO.setAddresses(BeanUtil.copyToList(addressList, AddressVO.class));
        return userVO;
    }

    @Override
    public void deductBalance(Long id, Integer amount) {
        //1、查询用户
        User user = this.getById(id);
        //2、判断用户是否存在及状态是否正常
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("用户不存在或已删除");
        }
        //3、判断余额是否充足
        if (user.getBalance() < amount) {
            throw new RuntimeException("余额不足");
        }
        //4、扣减余额
        baseMapper.deductBalance(id, amount);
        //预减余额
        int remainBalance = user.getBalance() - amount;

        //余额为0的时候修改状态为2
        //sql 语句：update user set balance = balance - #{amount}, status=2 where id = #{id} and balance = #{balance}
        //sql 语句：update user set balance = balance - #{amount} where id = #{id} and balance = #{balance}
        this.lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, 2)
                .eq(User::getBalance, user.getBalance())//乐观锁机制
                .eq(User::getId, id)
                .update();

    }
}
